<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--部门数据-->
      <el-col :span="4" :xs="24">
        <div class="head-container">
          <el-input
            v-model="deptName"
            placeholder="请输入组织名称"
            clearable
            size="small"
            prefix-icon="el-icon-search"
            style="margin-bottom: 20px"
          />
        </div>
        <div class="head-container">
          <el-tree
            :data="deptOptions"
            :props="defaultProps"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            ref="tree"
            default-expand-all
            @node-click="handleNodeClick"
          />
        </div>
      </el-col>

      <el-col :span="20" :xs="24">
        <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="100px">
          <el-form-item label="网关MAC" prop="zigbeeMac">
            <el-input
              v-model="queryParams.zigbeeMac"
              placeholder="请输入网关MAC"
              clearable
              size="small"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="手机号" prop="account">
            <el-input
              v-model="queryParams.account"
              placeholder="请输入手机号"
              clearable
              size="small"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery"
                       v-hasPermi="['device:gateway:query']"
            >搜索
            </el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            <el-button
              type="warning"
              icon="el-icon-download"
              size="mini"
              @click="handleExport"
              v-hasPermi="['device:gateway:export']"
            >导出
            </el-button>
          </el-form-item>
        </el-form>
        <el-col>
          <el-table v-loading="loading" :data="gatewayList" border @selection-change="handleSelectionChange">
            <!--            <el-table-column type="selection" width="55" align="center"/>-->
            <el-table-column label="主键" align="center" prop="id" v-if="false"/>
            <el-table-column label="手机号" align="center" prop="account" v-if="true" width="120"/>
            <el-table-column label="家庭名称" align="center" prop="homeName" :show-overflow-tooltip="true"/>
            <el-table-column label="网关MAC" align="center" prop="zigbeeMac" :show-overflow-tooltip="true"/>
            <el-table-column label="WiFiMAC" align="center" prop="wifiMac" :show-overflow-tooltip="true" v-if="false"/>
            <el-table-column label="WiFiIP" align="center" prop="wifiIp" :show-overflow-tooltip="true" v-if="false"/>
            <el-table-column label="网关名称" align="center" prop="name" :show-overflow-tooltip="true"/>
            <el-table-column label="自动入网" align="center" prop="zdrwbz" width="80">
              <template slot-scope="scope">
                <template v-if="scope.row.zdrwbz=='是'">
                  <div class="myTagOpen" style="margin-bottom: 2px">是</div>
                </template>
                <template v-else>
                  <div class="myTagClose">否</div>
                </template>
              </template>

            </el-table-column>
            <el-table-column label="布防状态" align="center" prop="defendStatus" width="80">
              <template slot-scope="scope">
                <template v-if="scope.row.defendStatus=='撤防'">
                  <div class="myTagClose" style="margin-bottom: 2px">撤防</div>
                </template>
                <template v-else>
                  <div class="myTagOpen">布防</div>
                </template>
              </template>
            </el-table-column>
            <el-table-column label="组织名称" align="center" prop="deptName" :show-overflow-tooltip="true"/>
            <el-table-column label="上报时间" align="center" prop="switchTime" :show-overflow-tooltip="true" width="180px">
              <!--<template slot-scope="scope">
                <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
              </template>-->
            </el-table-column>
            <!--            <el-table-column label="修改时间" align="center" prop="modifyTime" :show-overflow-tooltip="true">-->
            <!--              &lt;!&ndash; <template slot-scope="scope">-->
            <!--                 <span>{{ parseTime(scope.row.modifyTime, '{y}-{m}-{d}') }}</span>-->
            <!--               </template>&ndash;&gt;-->
            <!--            </el-table-column>-->


            <!--            <el-table-column label="用户详情" align="center" class-name="small-padding fixed-width">-->
            <!--              <template slot-scope="scope">-->
            <!--                &lt;!&ndash;popover弹出框&ndash;&gt;-->
            <!--                <el-popover-->
            <!--                  placement="top"-->
            <!--                  trigger="hover"-->
            <!--                >-->
            <!--                  <el-form ref="form" :model="form" :rules="rules" label-width="100px">-->
            <!--                    <el-row :span="12">-->
            <!--                      <el-tag>手机号</el-tag>-->
            <!--                      <el-tag type="success">{{ form.account }}</el-tag>-->
            <!--                    </el-row>-->
            <!--                    <el-row :span="12">-->
            <!--                      <el-tag>昵称</el-tag>-->
            <!--                      <el-tag type="success">{{ form.nickName }}</el-tag>-->
            <!--                    </el-row>-->
            <!--                  </el-form>-->
            <!--                  <el-button-->
            <!--                    size="mini"-->
            <!--                    type="text"-->
            <!--                    slot="reference"-->
            <!--                    icon="el-icon-chat-line-square"-->
            <!--                    @mouseenter.native="handleView(scope.row,scope.index)"-->

            <!--                  >用户详情-->
            <!--                  </el-button>-->
            <!--                </el-popover>-->
            <!--              </template>-->
            <!--            </el-table-column>-->
            <el-table-column label="操作" align="center" width="150">
              <template slot-scope="scope">
                <el-button size="mini" type="text" icon="el-icon-view" @click="handleDetails(scope.row)"
                           v-hasPermi="['device:gateway:detail']"
                >详情
                </el-button>
                <el-button size="mini" type="text" icon="el-icon-delete" @click="UntieHome(scope.row)"
                           v-hasPermi="['device:gateway:unbound']"
                >解绑
                </el-button>
                <el-button size="mini" type="text" icon="el-icon-s-tools" @click="SendCmd(scope.row)"
                           v-hasPermi="['device:gateway:cmdSend']"
                >指令
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum"
                      :limit.sync="queryParams.pageSize" @pagination="getList"
          />
        </el-col>
      </el-col>
    </el-row>


    <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body>
      <gatewayDetails :row="zigbeeMac"></gatewayDetails>
      <div slot="footer" class="dialog-footer">
        <el-button @click="open = false">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listGateway,
  delGateway,
  addGateway,
  updateGateway,
  exportGeteway,
  Untiegateway,
  sendCmd
} from '@/api/system/gateway'
import { deptTreeSelect } from '@/api/system/dept'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import gatewayDetails from '@/views/components/gateway/details'

export default {
  name: 'Gateway',
  components: { Treeselect, gatewayDetails },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 部门名称
      deptName: undefined,
      // 部门树选项
      deptOptions: undefined,
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 网关表格数据
      gatewayList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      zigbeeMac: undefined,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        zigbeeMac: undefined,
        account: undefined,
        deptId: undefined
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {}
    }
  },
  created() {
    this.getList()
    this.getTreeselect()
    this.getDictDataByType('sys_normal_disable').then(response => {
      this.statusOptions = response.data
    })
    this.getDictDataByType('sys_user_sex').then(response => {
      this.sexOptions = response.data
    })
    this.getConfigKey('sys.user.initPassword').then(response => {
      this.initPassword = response.msgname
    })
  },
  watch: {
    // 根据名称筛选部门树
    deptName(val) {
      this.$refs.tree.filter(val)
    }
  },
  methods: {
    /** 查询网关列表 */
    getList() {
      this.loading = true

      if (!this.queryParams.deptId) {
        // 取出当前用户的组织ID
        this.queryParams.deptId = this.$store.getters.deptId
      }

      listGateway(this.queryParams).then(response => {
        this.gatewayList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    /** 详细按钮操作 */
    handleView(row) {
      this.open = true
      this.form = row
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        homeId: undefined,
        zigbeeMac: undefined,
        wifiMac: undefined,
        wifiIp: undefined,
        name: undefined,
        createTime: undefined,
        modifyTime: undefined,
        zdrwbz: undefined,
        defendStatus: '0',
        alarmStatus: '0',
        imgUrl: undefined,
        switchTime: undefined,
        hardwareVersionNumber: undefined,
        softwareVersionNumber: undefined,
        manufacturerCode: undefined
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length != 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加网关'
    },
    /** 查询网关详情*/
    handleDetails(row) {
      this.open = true
      this.title = row.name + '详情'
      this.zigbeeMac = row.zigbeeMac
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.id != undefined) {
            updateGateway(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess('修改成功')
                this.open = false
                this.getList()
              }
            })
          } else {
            addGateway(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess('新增成功')
                this.open = false
                this.getList()
              }
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$confirm('是否确认删除网关编号为"' + ids + '"的数据项?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        return delGateway(ids)
      }).then(() => {
        this.getList()
        this.msgSuccess('删除成功')
      }).catch(function() {
      })
    },
    UntieHome(row) {
      const id = row.id
      this.$confirm('是否确认解绑' + row.account + '(' + row.homeName + ')的网关?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {

        return Untiegateway(id)
      }).then(() => {
        this.getList()
        this.msgSuccess('解绑成功')
      }).catch(function() {
      })
    },
    SendCmd(row) {
      const mac = row.zigbeeMac
      this.$prompt('请输入指令', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(({ value })=> {
        return sendCmd({cmd:value,gatewayMac:mac})
      }).then(() => {
        this.msgSuccess('发送成功')
      }).catch(()=>{
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams
      this.$confirm('是否确认导出?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        return exportGeteway(queryParams)
      }).then(response => {
        this.download(response.msg)
      }).catch(function() {
      })
    },

    /** 查询部门下拉树结构 */
    getTreeselect() {
      deptTreeSelect().then(response => {
        this.deptOptions = response.data
      })
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.selectedOrgCode = data.id
      this.queryParams.deptId = data.id
      this.getList()
    }

  }
}
</script>
